<template>
	<view id="taskComplete">

		<view class="serach">
			<input class="input" v-model="key" placeholder="请输入关键字查询" @iconClick="iconClick" />
			<view class="mini-btn" @click="openPopup">筛选</view>
		</view>
		<view class="content">
			<uni-card v-for="item in cardData" :key="item.id" title="基础卡片" sub-title="副标题" extra="额外信息" padding="10px 0"
				:thumbnail="avatar" @click="gotoTaskDetail(item)">
				<template v-slot:title>
					<view class="title">
						<view class="title-name">
							<span>{{ item.name }}</span>
							<view class="timeStuas" v-if="item.taskType === 1&&item.endtime"
								style="border: 1px solid #22d01c; color: #22d01c">
								{{ item.endtime }}小时后超时
							</view>
							<view class="timeStuas" v-else-if="item.taskType === 3"
								style="border: 1px solid #ff0000; color: #ff0000">
								超时{{ item.endtime }}小时
							</view>
						</view>
						<view class="status">
							<view v-if="item.taskType === 0" style="background-color: #d4d4d4">
								待开始
							</view>
							<view v-else-if="item.taskType === 1" style="background-color: #e8d102">
								进行中
							</view>
							<view v-else-if="item.taskType === 2" style="background-color: #22d01c">
								已完成
							</view>
							<view v-else style="background-color: #f56c6c">
								已逾期
							</view>
						</view>
					</view>
				</template>
				<view class="mainContent">
					<view class="mcP">
						<view class="mcP-title">任务类型：</view>
						<span v-for="(el, inex) in item.taskTypes" :key="inex">{{ el.name + '' }}
						</span>
					</view>
					<view class="mcP">
						<view class="mcP-title">任务内容：</view><span>{{ item.content }}</span>
					</view>
					<view class="mcP">
						<view class="mcP-title">负责人：</view><span>{{ item.responsibleUser.name }}</span>
					</view>
					<view class="mcP">
						<view class="mcP-title">截止日期：</view><span>{{ item.taskEndTime }}</span>
					</view>
				</view>
				<view slot="actions">
					<view class="mainContent">
						<view style="border-top: 4rpx solid #bebebe"> </view>
						<view class="mcP bottm" style="margin-top: 0.8rem">
							<view class="mcP-title bottm-text">{{
                item.createUserName
              }}</view>
							<view class="bottm-text">{{ item.createTime }}</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<view style="
        width: 100vw;
        height: 40rpx;
        margin: 40rpx 0;
        color: #bebebe;
        font-size: 0.8rem;
        text-align: center;
      ">
			<uni-load-more color="#007AFF" :status="status" />
		</view>
		<uv-popup ref="popup" @change="change">
			<view class="popupfrom">
				<uni-forms :modelValue="formData" style="margin: 0 auto">
					<uni-forms-item label="任务类型" name="name" label-width="100px">
						<uni-data-select style="width: 100%" v-model="formData.type"
							:localdata="typeList"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="任务开始时间" name="taskStartTime" label-width="100px">
						<view class="example-body">
							<uni-datetime-picker style="width: 100%" type="date" v-model="formData.taskStartTime" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="任务结束时间" name="taskEndTime" label-width="100px">
						<view class="example-body">
							<uni-datetime-picker style="width: 100%" type="date" v-model="formData.taskEndTime" />
						</view>
					</uni-forms-item>
				</uni-forms>
				<button @click="serch()">确认</button>
			</view>
		</uv-popup>
	</view>
</template>

<script>
	import {
		getTaskInfoPage
	} from '@/api/user.js'
	import {
		baseURL
	} from '@/api/env.js'
	export default {
		data() {
			return {
				formData: {
					taskStartTime: null,
					taskEndTime: null,
					type: null,
				},
				year: new Date().getFullYear(),
				month: new Date().getMonth() + 1,
				nowMonth: new Date().getMonth() + 1,
				toDay: new Date().getDate(),
				taskStartTime: '',
				taskEndTime: '',
				searchInput: '',
				cardData: [],
				total: 0, //总共多少条数据
				pageNum: 1,
				pageSize: 5,
				key: null,
				status: 'more',
				list: [{
						name: '全部',
						value: 0,
						number: 0,
						icon: 'person',
					},
					{
						name: '已完成',
						value: 2,
						number: 0,
						icon: 'home',
					},
					{
						name: '进行中',
						value: 1,
						number: 1,
						icon: 'calendar',
					},
					{
						name: '已逾期',
						value: 3,
						number: 1,
						icon: 'map-pin-ellipse',
					},
				],
				active: 0,
				taskType: null,
				typeList: [],
				timer: null,
			}
		},
		onShow() {
			//没次回到页面都会调用下拉刷新
			// uni.startPullDownRefresh()
		},
		onLoad() {
			console.log(baseURL, 'baseURL');
			//页面最开始调用
			// this.taskStartTime = this.year + '-' + this.month + '-' + this.toDay
			// this.taskStartTime = "2023-11-13 23:59:59"
			// this.getTaskCountListApi(this.taskStartTime)
			this.cardData = []
			this.pageNum = 1
			this.pageSize = 5

			this.getData()
			// this.$nextTick(() => {
			// 	uni.stopPullDownRefresh();

			// });
			this.init()
		},
		watch: {
			active(newVal, oldVal) {
				if (newVal == 0) {
					this.taskType = null
				} else {
					this.taskType = newVal
				}
				this.cardData = []
				this.pageNum = 1
				this.pageSize = 5

				this.getData()
			},
			key(newVal, oldVal) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.cardData = []
					this.pageNum = 1
					this.pageSize = 5
					this.getData()
				}, 1500)
			},
		},
		methods: {
			serch() {
				this.cardData = []
				this.pageNum = 1
				this.pageSize = 5
				this.getData()
			},
			//初始化
			init() {
				uni.request({
					url: baseURL + '/api/task/type/list',
					method: 'GET',
					header: {
						// "content-type": "appLication/x-www-form-urlencoded",
						Authorization: uni.getStorageSync('token'),
					},
					success: (res) => {
						console.log('ssssss', res.data.data)
						this.typeList = res.data.data.map((option) => {
							return {
								value: option.type,
								text: option.name,
							}
						})
					},
				})
			},
			changeTab(index) {
				console.log('当前选中的项：' + index)
			},
			openPopup() {
				console.log(this.$refs.popup)
				this.$refs.popup.open('bottom')
			},
			change(e) {
				console.log('弹窗状态改变：', e)
			},

			getDaysInMonth(dateString) {
				// 创建一个表示指定日期的 Date 对象
				const date = new Date(dateString)

				// 获取月份
				const month = date.getMonth() + 1 // 月份从 0 开始，所以需要加 1
				// 获取指定月份的天数
				const year = date.getFullYear()
				const daysInMonth = new Date(year, month, 0).getDate()

				return daysInMonth
			},
			// 查看详情
			gotoTaskDetail(item) {
				item.disable = true
				uni.navigateTo({
					url: '/pages/taskMg/taskList/taskDetail/taskDetail?item=' +
						JSON.stringify(item),
				})
			},
			// 查询
			searchHandler() {
				this.getData()
			},
			// 搜索
			submitForm() {
				console.log(this.formData)
				this.cardData = []
				this.getData()
			},
			// 加载数据的方法
			getData() {
				let that = this
				let startTime = ""
				let endTime = ""
				if (this.formData.taskEndTime && this.formData.taskStartTime) {
					startTime = this.formData.taskStartTime + ' ' + '00:00:00'
					endTime = this.formData.taskEndTime + ' ' + '23:59:59'
				} else {
					if (this.formData.taskEndTime) {
						endTime = this.formData.taskEndTime + ' ' + '23:59:59'
					} else if (this.formData.taskStartTime) {
						startTime = this.formData.taskStartTime + ' ' + '23:59:59'
					}
				}
				let params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					taskStartTime: startTime,
					taskEndTime: endTime,
					key: this.key,
					taskType: this.taskType,
					createUserId: uni.getStorageSync('userId'),
					type: this.formData.type
				}
				Object.keys(params).forEach(key => {
					if (params[key] === null) {
						delete params[key];
					}
				});
				console.log(params.createUserId)
				getTaskInfoPage(params).then((res) => {
					if (res.code == 200) {
						if (res.data.records.length == 0) {
							uni.showToast({
								title: '暂无任务',
								icon: '', //将值设置为 success 或者 ''
								duration: 1500, //持续时间为 2秒
							})
						} else {
							let time = ''
							res.data.records.forEach((el) => {
								el.endtime = that.timeCalculation(el)
								this.cardData.push(el)
							})
							console.log(this.cardData)
						}

						this.total = res.data.total
					}
				})
			},
			/**
			 *接口
			 * /
			 */
			getTaskCountListApi(taskStartTime = '', taskEndTime = '') {
				console.log(this.startTime)
				let params = []
				if (taskStartTime == '') {
					params = {
						taskStartTime: this.startTime,
						taskEndTime,
					}
				} else {
					params = {
						taskStartTime,
						taskEndTime,
					}
				}
				console.log('params', params)
				let queryString = Object.entries(params)
					.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
					.join('&')
				uni.request({
					url: baseURL + '/api/task/info/count/list?' + queryString,
					method: 'GET',
					header: {
						// "content-type": "appLication/x-www-form-urlencoded",
						Authorization: uni.getStorageSync('token'),
					},
					success: (res) => {
						console.log('ssssss', res.data.data)
						let a = res.data.data[0].taskInfoCount
						this.numData[0].num = a.completeCount
						this.numData[1].num = a.doingCount
						this.numData[2].num = a.overdueCount
						console.log(a.completeCount, a.doingCount, a.overdueCount)
						if (
							a.completeCount == 0 &&
							a.doingCount == 0 &&
							a.overdueCount == 0
						) {
							this.numData[3].num = '--%'
						} else {
							this.numData[3].num =
								(
									(a.completeCount /
										(a.completeCount + a.doingCount + a.overdueCount)) *
									100
								).toFixed(2) + '%'
						}
					},
				})
				// getTaskCountList(params).then(res => {
				// 	console.log('统计res', res);
				// 	if (res.code == 200) {

				// 	}
				// })
			},
			timeCalculation(endTime) {
				const now = new Date()
				const year = now.getFullYear()
				const month = String(now.getMonth() + 1).padStart(2, '0')
				const day = String(now.getDate()).padStart(2, '0')
				const hours = String(now.getHours()).padStart(2, '0')
				const minutes = String(now.getMinutes()).padStart(2, '0')
				const seconds = String(now.getSeconds()).padStart(2, '0')
				const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
				console.log(formattedDate)
				var date1 = new Date(formattedDate)
				var date2 = new Date(endTime.taskEndTime)

				// console.log(timeFn, endTime)

				const timestamp1 = date1.getTime()
				const timestamp2 = date2.getTime()

				const millisecondDiff = Math.abs(timestamp2 - timestamp1)
				const hourDiff = Math.ceil(millisecondDiff / (1000 * 60 * 60))
				console.log((endTime))
				let finalTime
				endTime.type.forEach(item => {
					if (item == "4") {
						if (hourDiff <= 6) {
							finalTime = hourDiff
							return
						}
					}
					if (item == "3") {
						if (hourDiff <= 12) {
							finalTime = hourDiff
							return
						}
					}

				})
				if (endTime.taskType == "3") {
					finalTime = hourDiff
				}
				console.log(finalTime)
				if (finalTime) {
					return finalTime
				}

			},
		},
		// 上拉加载
		onReachBottom() {
			uni.showToast({
				icon: 'none',
				title: '正在加载更多',
			})
			let allTotal = this.pageNum * this.pageSize
			if (allTotal < this.total) {
				this.status = 'loading'
				//当前条数小于总条数 则增加请求页数
				this.pageNum++
				this.getData() //调用加载数据方法
			} else {
				this.status = 'noMore'
				// console.log('已加载全部数据')
			}
		},
		//下拉刷新
		onPullDownRefresh() {
			this.list = []
			//调用获取数据方法
			this.getData(1, 5, this.taskStartTime)
			setTimeout(() => {
				//结束下拉刷新
				uni.stopPullDownRefresh()
			}, 1000)
		},
	}
</script>

<style scoped lang="scss">
	#taskComplete {
		.sta {
			// background-color: #409EFF;
			color: white;
			padding: 40rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;

			.staCard {
				display: flex;
				flex-direction: column;
				align-items: center;

				.sFont {
					font-weight: 300;
				}

				.mFont {
					font-size: 1.6rem;
					margin: 20rpx 0;
				}
			}
		}

		.serach {
			width: 100vw;
			height: 60rpx;
			display: flex;
			flex-direction: row;
			padding: 10rpx;

			.input {
				width: 85%;
				height: 60rpx;
				border-radius: 30rpx;
				padding-left: 40rpx;
				background-color: white;
				border: 1rpx solid #c2c2c2;
			}

			.mini-btn {
				width: 15%;
				height: 60rpx !important;
				line-height: 60rpx;
				text-align: center;
				color: #409eff;
				// border: 1rpx solid #c2c2c2;
			}
		}

		.content {
			margin-top: -10rpx;
			width: 100vw;
			font-size: 28rpx;

			.title {
				padding: 10rpx 0;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
			}

			.title,
			.status,
			.title-name {
				height: 40rpx;
				position: relative;

				span {
					width: 250rpx;
					text-overflow: ellipsis;
					display: inline-block;
					overflow: hidden;
				}

				.timeStuas {
					position: absolute;
					right: -200rpx;
					top: 0rpx;
					width: 200rpx;
					border-radius: 10rpx;
					text-align: center;
				}
			}

			.status {
				width: 120rpx;
				color: #fff;
				text-align: center;

				view {
					height: 40rpx;
					line-height: 40rpx;
					font-size: 12px;
					border-radius: 20rpx;
					padding: 8rpx 16rpx;
				}
			}

			.mainContent {
				font-size: 28rpx;

				.mcP {
					display: flex;
					flex-direction: row;

					.mcP-title {
						width: 25%;
						color: #c2c2c2;
					}

					.bottm {
						display: flex;
						flex-direction: row;
					}

					.bottm-text {
						// font-size: 0.9rem;
						color: #c2c2c2;

						height: 60rpx;
						line-height: 60rpx;
					}
				}
			}
		}

		.popupfrom {
			width: 80%;
			margin: 0 auto;
			padding: 10rpx;
			padding-top: 30rpx;

			.uni-forms-item {
				margin-bottom: 15rpx;
			}
		}
	}
</style>